package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.com.dashihui.web.dao.Store;

public class StoreService {
	
	public boolean findExistsByUsername(String username){
		return Store.me().findFirst("SELECT * FROM t_dict_store WHERE username=?",username)!=null;
	}
	
	public Store findByUsername(String username){
		return Store.me().findFirst("SELECT * FROM t_dict_store WHERE username=?",username);
	}
	
	public boolean sortStore(Map<String,String> sortMap){
		int batchSize = sortMap.size();
		List<String> sqlList = new ArrayList<String>();
		for(String id : sortMap.keySet()){
			sqlList.add("UPDATE t_dict_store SET orderNo="+sortMap.get(id)+" WHERE id="+id);
		}
		int[] result = Db.batch(sqlList,batchSize);
		return result.length>0;
	}
	
	public boolean addStore(Store newObject){
		return newObject.save();
	}
	
	public boolean delStore(int id){
		return Store.me().deleteById(id);
	}
	
	public boolean editStore(Store object){
		return object.update();
	}
	
	public Store findById(int id){
		return Store.me().findFirst("SELECT store.*,p.name provinceName,c.name cityName,a.name areaName FROM t_dict_store store LEFT JOIN t_dict_city p ON store.province=p.id LEFT JOIN t_dict_city c ON c.id=store.city LEFT JOIN t_dict_city a ON a.id=store.area WHERE store.id=?",id);
	}
	
	@Before(Tx.class)
	public boolean editMinePwd(Store currentUser,String passwordOld,String passwordNew) throws Exception{
		Store user = Store.me().findById(currentUser.getInt("id"));
		if(user==null){
			return false;
		}
		PasswordService svc = new DefaultPasswordService();
		if(!svc.passwordsMatch(passwordOld, user.getStr("password"))){
			throw new Exception("原密码输入不正确");
		}else{
			return user.set("password", svc.encryptPassword(passwordNew)).update();
		}
	}
	
	public Community findCommunity(int storeid){
		return Community.me().findFirst("SELECT * FROM t_dict_community WHERE storeid=?",storeid);
	}
}
